<template>
  <div ref="chartRef" style="width: 100%; height: 100%"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  BarChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  CanvasRenderer
])

const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  xKey: {
    type: String,
    default: 'name'
  },
  yKey: {
    type: String,
    default: 'value'
  },
  title: String,
  color: {
    type: String,
    default: '#6a8cff'
  }
})

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  updateChart()
}

const updateChart = () => {
  if (!chart) return
  
  const option = {
    title: props.title ? {
      text: props.title,
      left: 'left',
      textStyle: {
        color: '#475569'
      }
    } : undefined,
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: props.data.map((item: any) => item[props.xKey])
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: props.data.map((item: any) => item[props.yKey]),
      type: 'bar',
      itemStyle: {
        color: props.color,
        borderRadius: [4, 4, 0, 0]
      },
      barWidth: '40%'
    }],
    grid: {
      containLabel: true,
      left: '3%',
      right: '3%',
      bottom: '3%'
    }
  }
  
  chart.setOption(option)
}

// 定义处理窗口大小变化的函数
const handleResize = () => {
  chart?.resize()
}

onMounted(() => {
  initChart()
  // 监听窗口大小变化事件
  window.addEventListener('resize', handleResize)
})

watch(() => props.data, updateChart)

onBeforeUnmount(() => {
  chart?.dispose()
  // 移除窗口大小变化事件监听
  window.removeEventListener('resize', handleResize)
})
</script>
